<template>
  <div ref="tableSelect" class="box">
    <div class="tableSelect">
      <div class="flex flex-row iptBox" :class="{'is-active':(showTable)}">
        <input v-model="showName" :placeholder="placeholder" @change="emitName" @focus="jumpKey" @keyup.enter="setKeyword"><div class="delIcon"><i class="el-icon-delete" @click="removeValue" /></div><div class="flex j-content a-item" @click="showTable = !showTable"><i v-if="!showTable" class="el-icon-arrow-down down" /><i v-else class="el-icon-arrow-up down" /></div>
      </div>
      <div v-show="showTable" class="tableContent">
        <div class="flex flex-row tableContent-iptBox">
          <div class="flex flex-row "><div style="width: 100px">输入内容:</div><el-input ref="keyInput" v-model="keyword" class="ipt" /></div>
          <!--        <div><el-button type="primary" @click="queryInit">查询</el-button></div>-->
        </div>
        <el-table
          ref="table"
          :data="tableData"
          border
          height="220"
          :style="{width: width + 'px'}"
          highlight-current-row
          @current-change="setRedioVal"
          @row-click="selectRow"
          @selection-change="setVal"
        >
          <el-table-column v-if="multiple" type="selection" width="60" />
          <el-table-column type="index" width="60" label="序号" />
          <el-table-column
            v-for="item in tableColumns"
            :prop="item.prop"
            :label="item.label"
            :width="item.width || 180"
          />
        </el-table>
        <el-pagination
          :current-page.sync="page.page"
          :page-size="page.size"
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import {number} from "echarts/lib/export";

export default {
  name: 'TableSelect',
  props: {
    url: {
      type: String
    },
    // 需要显示的列 格式:[{prop:goodsName,label:'商品名称'},{prop:goodsCode,label:'商品编码'}]
    tableColumns: {
      type: Array
    },
    // 查询条件
    params: {
      type: Object
    },
    // 请求类型
    queryType: {
      type: String,
      default: 'get'
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    // 绑定值
    value: {
      type: [Object, String, Number],
      default:""
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    width: {
      type: [String, Number],
      default: 500
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否切换输入框
    isTab: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      total: 0,
      tableData: [],
      showTable: false,
      page: {
        page: 1,
        size: 50
      },
      isActive: false,
      keyword: '',
      showName: '',
      currentSelect: [],
      historySelect: [],
      historyObject: []
    }
  },
  watch: {
    value(n) {
      if (!n) {
        this.removeValue()
      }
    },
    keyword(n) {
      this.page.page = 1
      this.historySelect = [...this.historySelect, ...this.currentSelect]
      this.historyObject = this.historySelect.map(item => JSON.parse(item))
      this.onGet()
    }
  },
  created() {
    this.onGet()
  },
  mounted() {
    document.addEventListener('click', this.outClick)
  },
  methods: {
    queryInit() {
      this.page.page = 1
      this.historySelect = [...this.historySelect, ...this.currentSelect]
      this.historyObject = this.historySelect.map(item => JSON.parse(item))
      this.onGet()
    },
    onGet() {
      const data = { ...this.params, ...this.page, keyword: this.keyword }
      const val = this.keyword
      if (this.queryType === 'get') {
        request({
          url: this.url,
          method: this.queryType,
          params: data
        }).then(res => {
          if (this.keyword !== val) {
            return
          }
          const list = []
          this.tableData = res.content || res.data.content
          this.total = res.totalElements || res.data.totalElements
          const _this = this
          setTimeout(() => {
            for (const i in _this.tableData) {
              const index = _this.historySelect.indexOf(JSON.stringify(_this.tableData[i]))
              if (index !== -1) {
                list.push(_this.tableData[i])
                _this.historySelect.splice(index, 1)
              }
            }
            _this.historyObject = _this.historySelect.map(item => JSON.parse(item))
            _this.$nextTick(function() {
              list.forEach(row => {
                _this.$refs.table.toggleRowSelection(row)
              })
            })
          })
        })
      } else if (this.queryType === 'post') {
        request({
          url: this.url,
          method: this.queryType,
          data
        }).then(res => {
          this.tableData = res.content
          console.log(this.tableData)
        })
      }
    },
    outClick(e) {
      const userRef = this.$refs.tableSelect
      try {
        if (userRef && !userRef.contains(e.target) && this.showTable) {
          this.showTable = false
        }
      } catch (err) {}
    },
    jumpKey() {
      this.showTable = true
      if (this.isTab) {
        setTimeout(() => { this.$refs.keyInput.focus() }, 100)
        this.historySelect = [...this.historySelect, ...this.currentSelect]
        this.historyObject = this.historySelect.map(item => JSON.parse(item))
        this.onGet()
      }
    },
    selectRow(row) {
      if (this.multiple) {
        this.$refs['table'].toggleRowSelection(row)
      }
    },
    emitName() {
      this.$emit('changeVal', this.showName)
    },
    setKeyword() {
      if (!this.value) {
        this.keyword = this.showName
        this.onGet()
      }
      this.showTable = true
    },
    handleCurrentChange(val) {
      this.historySelect = [...this.historySelect, ...this.currentSelect]
      this.historyObject = this.historySelect.map(item => JSON.parse(item))
      this.currentSelect = []
      this.page.page = val
      this.onGet()
    },
    removeValue() {
      // this.showName = null
      this.showName = ''
      this.$emit('update:value', '')
      this.toggleSelection()
      this.currentSelect = []
      this.historySelect = []
    },
    toggleSelection(rows) {
      this.$refs.table.clearSelection()
    },
    setRedioVal(row) {
      this.showName = row[this.labelKey]
      this.value = row[this.valueKey]
      this.$emit('update:value', this.value)
      this.$emit('change', row)
      this.showTable = false
    },
    setVal(val) {
      const list = [...this.historyObject, ...val]
      this.showName = Array.from(new Set(list.map(item => item[this.labelKey]))).join(',')
      const value = Array.from(new Set(list.map(item => item[this.valueKey]))).join(',')
      this.currentSelect = val.map(item => JSON.stringify(item))
      console.log(value)
      this.$emit('update:value', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style lang="scss" scoped>
.box{
  z-index:999;
  .tableSelectBox{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
.tableContent{
  background-color: #ffffff;
  border: rgb(200,200,200) solid 1px;
  position: absolute;
  z-index: 9999;
 }
.tableContent-iptBox{
  padding: 10px;
  div{
    margin-right: 20px;
  }
}
.iptBox{
  border: rgba(203,203,203,0.6) solid 1px;
  padding: 2px;
  border-radius: 4px;
  height: 30px;
  .delIcon{
    display: none;
  }
  input{
    border: none;
    width: 100%;
    outline:none;
    font-family: 宋体;
  }
  i{
    font-size: 18px;
    cursor: pointer;
    float: right;
    padding: 3px;
    color: rgba(203,203,203,1);
  }
}
input::-webkit-input-placeholder{ /*WebKit browsers*/

  color: rgba(203,203,203,1);
  padding-left: 10px;
  font-family: 微软雅黑;
}

.iptBox:hover .delIcon{
  display: block;
}
.is-active{
  border: #409eff 1px solid;
}

</style>
